package com.doeis.common.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
	
	private static SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
	private static SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
	private static SimpleDateFormat secFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static String formatTime(long t, boolean shortable){
		Calendar c = Calendar.getInstance();
		SimpleDateFormat formatter = null;
		
		String now = dayFormat.format(c.getTime());
		c.setTimeInMillis(t);
		String tTime = dayFormat.format(c.getTime());
		
		//同一天就使用短的
		if( now.equals(tTime) && shortable){
			formatter = hourFormat;
		}else{
			formatter = secFormat;
		}
		
		String dateString = formatter.format(c.getTime());
		return dateString;
	}
	
	public static String formatTime(long t){
		return formatTime(t,true);
	}
	
	public static String formatTime(Timestamp time, boolean shortable){
		return formatTime(time.getTime(), shortable);
	}
	
	public static String formatTime(Timestamp time){
		return formatTime(time.getTime(),true);
	}
	
	public static String formatTime(Timestamp time, String format){
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return formatter.format(time);
	}
		
	/**
	  * 类型转换
	  * @param dateStr
	  * @return
	  * @throws Exception
	  */
	public final static Timestamp strToDateTime(String dateStr){  
	    int len = dateStr.length();  
	    String format = "yyyy-MM-dd HH:mm:ss.SSS".substring(0, len);  
	    DateFormat df = new SimpleDateFormat(format);  
	    Date timeDate = null;
	    Timestamp dateTime = null;
			try {
				timeDate = df.parse(dateStr);
				dateTime = new java.sql.Timestamp(timeDate.getTime());// sql类型  
			} catch (ParseException e) {
				e.printStackTrace();
			}  
	    return dateTime;  
	}
	
	/**
	 * 取当前时间
	 * @return
	 */
	public static Timestamp currentDateTime(){
		return new Timestamp(System.currentTimeMillis());
	}
	
	public static String currentStrTime(){
		return formatTime(currentTime());
	}
	
	public static long currentTime(){
		return System.currentTimeMillis();
	}
	
	public static Timestamp longToTimestamp(long t){
		return new Timestamp(t);
	}
}
